import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

// Define our MCP agent with tools
export class MyMCP extends McpAgent {
	server = new McpServer({
		name: "Google Image Search",
		version: "1.0.0",
	});

	async init() {
		// Call SearchAPI for Google Images
		this.server.tool(
			"google_image",
			{
				query: z.string(),
				size: z.enum([
					"large", "medium", "icon", "larger_than_400x300", 
					"larger_than_640x480", "larger_than_800x600", "larger_than_1024x768", 
					"larger_than_2mp", "larger_than_4mp", "larger_than_6mp", 
					"larger_than_8mp", "larger_than_12mp", "larger_than_15mp", 
					"larger_than_20mp", "larger_than_40mp", "larger_than_70mp"
				]).optional(),
				image_type: z.enum([
					"clipart", "line_drawing", "gif", "face", "photo"
				]).optional(),
				aspect_ratio: z.enum([
					"square", "tall", "wide", "panoramic"
				]).optional(),
				gl: z.string().optional()
			},
			async ({ query, size, image_type, aspect_ratio, gl }) => {
				console.info("Searching for: " + query);
				
				try {
					// Get API key from environment variables
					const apiKey = this.env.SEARCHAPI_KEY;
					if (!apiKey) {
						return {
							content: [
								{ type: "text", text: "Error: SEARCHAPI_KEY is not set in environment variables" }
							],
						};
					}
					
					// Call SearchAPI
					// Build query string with optional parameters
					let url = `https://www.searchapi.io/api/v1/search?engine=google_images&q=${encodeURIComponent(query)}`;
					
					// Add optional parameters if they exist
					if (size) url += `&size=${encodeURIComponent(size)}`;
					if (image_type) url += `&image_type=${encodeURIComponent(image_type)}`;
					if (aspect_ratio) url += `&aspect_ratio=${encodeURIComponent(aspect_ratio)}`;
					
					// Use provided gl parameter or default to 'cn'
					const glValue = gl || 'cn';
					url += `&gl=${encodeURIComponent(glValue)}`;
					
					const response = await fetch(url, {
						method: "GET",
						headers: {
							"Authorization": `Bearer ${apiKey}`
						}
					});
					
					if (!response.ok) {
						return {
							content: [
								{ type: "text", text: `Error: ${response.status} ${response.statusText}` }
							],
						};
					}
					
					// Parse JSON response
					const data = await response.json();
					
					// Extract the first image's original link
					if (data.images && data.images.length > 0) {
						const firstImageLink = data.images[0].original?.link;
						if (firstImageLink) {
							return {
								content: [
									{ type: "text", text: firstImageLink }
								],
							};
						}
					}
					
					return {
						content: [
							{ type: "text", text: "No images found in the response" }
						],
					};
				} catch (error) {
					return {
						content: [
							{ type: "text", text: `Error: ${error.message}` }
						],
					};
				}
			}
		);
	}
}

export default {
	fetch(request: Request, env: Env, ctx: ExecutionContext) {
		const url = new URL(request.url);

		if (url.pathname === "/sse" || url.pathname === "/sse/message") {
			return MyMCP.serveSSE("/sse").fetch(request, env, ctx);
		}

		if (url.pathname === "/mcp") {
			return MyMCP.serve("/mcp").fetch(request, env, ctx);
		}

		return new Response("Not found", { status: 404 });
	},
};
